package com.yxe.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.yxe.api.CommonResult;
import com.yxe.dto.SubletDto;
import com.yxe.dto.SubletVo;
import com.yxe.service.SubletService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@Api(tags = "转租模块")
@Slf4j
@RequestMapping("sublet")
public class SubletController {

    @Autowired
    private SubletService subletService;




    @GetMapping("findById")
    @ApiOperation("转租记录")
    public CommonResult findById(){

        //拿到当前用户uid
        int uid = StpUtil.getLoginIdAsInt();


        List<SubletDto> dtoList = subletService.findById(uid);

        ArrayList<SubletDto> arrayList = new ArrayList<>(dtoList.size());

        if (dtoList != null) {

            for (SubletDto subletDto : dtoList) {
                Integer status = subletDto.getStatus();

                if (status.equals(0)) {
                    subletDto.setStatue("已申请");
                } else if (status.equals(1)) {
                    subletDto.setStatue("批准");
                } else {
                    subletDto.setStatue("未批准");
                }

                // 将每一次结果存储到集合中
                arrayList.add(subletDto);
            }

            return CommonResult.success(arrayList);
        }

        return CommonResult.failed("暂无转租记录");

    }

    @PostMapping("addSubject")
    @ApiOperation("添加转租记录")
    public CommonResult addSubject(@ApiParam("转租申请对象") @RequestBody SubletVo subletVo){
      int uid = StpUtil.getLoginIdAsInt();
//       Integer uid = 6;
        subletVo.setUid(uid);

        subletService.addSublet(subletVo);

        return CommonResult.success("申请转租成功");
    }

    @GetMapping("findSubletRecord")
    @ApiOperation("查看转租申请记录")
    public CommonResult findSubletRecord(){
        SubletVo subletVo = subletService.findSubletRecord(StpUtil.getLoginIdAsInt());

        if (subletVo != null){
           return CommonResult.success(subletVo);
        }

       return CommonResult.failed("没有转租记录");
    }

    @DeleteMapping("deleteSubletRecord")
    @ApiOperation("撤销转租申请")
    public CommonResult deleteSubletRecord(){
        int uid = StpUtil.getLoginIdAsInt();

        subletService.deleteSubletRecord(uid);

        if (subletService.findSubletRecord(uid) != null){
            return CommonResult.success("删除成功");

        }
        return CommonResult.failed("删除失败");
    }



}
